<?php

class AjaxController extends Controller {

    public function actionSaveCoordinates() {
        $lng = $_GET['lng'];
        $lat = $_GET['lat'];
        $id = $_GET['id'];
        $com = Company::model()->findByPk($id);
        $com->lng = $lng;
        $com->lat = $lat;
        if (!$com->save()) {
            var_dump($com->getErrors());
        }

    }

    public function actionGetAll() {
        $coms = Company::model()->findAll(array(
            'select' => '*',
            'condition' => 'lng = ""',
//            'params' => array('lng' => '')
        ));
        $results = array();
        foreach ($coms as $com) {
            array_push($results, array('id' => $com->id, 'address' => $com->address . ' ' . $com->city));
        }
        return $this->_response(array('results' => $results));
    }

    public function actionLoadData() {
        if (!isset($_POST['lng'])) {
            return;
        }

        if (!isset($_POST['lat'])) {
            return;
        }
        $page_index = isset($_POST['page_index']) ? $_POST['page_index'] : 0;
        $page_size = Yii::app()->params['page_size'];
        $connection = Yii::app()->db;

        $cat_id = isset($_POST['cat_id']) ? $_POST['cat_id'] : 0;
        $lng = trim($_POST['lng']);
        $lat = trim($_POST['lat']);

        $lng_point = end(array_filter(explode('.', $lng)));

        $lat_point = end(array_filter(explode('.', $lat)));

        $small_lng = intval(floor($lng)) - 1 + floatval('0.' . ($lng_point));
        $small_lat = intval(floor($lat)) - 1 + floatval('0.' . ($lat_point));

        $big_lng = floatval($small_lng) + 3;
        $big_lat = floatval($small_lat) + 3;

        $offset = $page_index * $page_size;

        $query = "select t.id,t.lng,t.lat,t.name,t.owner,t.address,t.category_id,t.picture,t.city,t.phone,t.zipcode, c.name_vn as category_name,(
                    ROUND(( 3959 * acos( cos( radians($lat) ) *
                    cos( radians( t.lat ) ) *
                    cos( radians( t.lng ) -
                    radians($lng) ) +
                    sin( radians($lat) ) *
                    sin( radians( t.lat ) ) ) ) ,2)+0.2 )
                    AS distance
            from company t
            inner join category c on c.id = t.category_id
            where t.published = 1  and (t.lng > {$small_lng} and t.lng < {$big_lng}) and (t.lat > {$small_lat} and t.lat < {$big_lat})
             order by distance ASC
            limit {$page_size} offset {$offset}

        ";

        $query_total = "select count(*) as count
            from company t
             where t.published = 1 and (t.category_id = {$cat_id} or {$cat_id} = 0) and (t.lng > {$small_lng} and t.lng < {$big_lng}) and (t.lat > {$small_lat} and t.lat < {$big_lat})
        ";
        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        $total_command = $connection->createCommand($query_total);
        $total = $command = $total_command->queryRow();
        $cur_address = '';
        //don't work on server?????
//        if ($_POST['is_cur_location']) {
//            $url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&key=' . Yii::app()->params['API_key'];
//            if ($response = HSCommon::curl($url)) {
//                $response = json_decode($response);
//                $cur_address = $response->results[0]->formatted_address;
//            }
//
//        }
        $ads = array();
        if (count($results) > 0) {
            $zipcode = $results[0]['zipcode'];
            $ads = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.zipcode = '{$zipcode}' and published = 1 order by id DESC")->queryRow();;
        }

        return $this->_response(array(
            'results' => $results,
            'cur_lat' => $lat,
            'cur_lng' => $lng,
            'total' => $total,
            'cur_address' => $cur_address,
            'ads' => $ads
        ));

    }

    public function actionSearchCompany() {
        if (!isset($_GET['keywords'])) return;

        $lng = isset($_GET['lng']) ? $_GET['lng'] : '';
        $lat = isset($_GET['lat']) ? $_GET['lat'] : '';

        $keywords = (trim($_GET['keywords']));
        $name_keywords = "%$keywords%";
        $phone_keywords = str_replace(' ', '-', $keywords);
        $connection = Yii::app()->db;
        $is_utf8 = HSCommon::detectUTF8($keywords);
        $results = array();
        if ($is_utf8) {

            if ($lng == '' && $lat == '') {
                $query = "
                    select *
                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') collate utf8_bin or c.phone like '{$phone_keywords}' )
                    limit 50";
            } else {
                $query = "
                    select *,  (
                        ROUND(( 3959 * acos( cos( radians($lat) ) *
                                cos( radians( c.lat ) ) *
                                cos( radians( c.lng ) -
                                    radians($lng) ) +
                                sin( radians($lat) ) *
                                sin( radians( c.lat ) ) ) ) ,2)+0.2 )
                        AS distance

                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') collate utf8_bin or c.phone like '{$phone_keywords}' )
                    order by distance ASC
                    limit 50
        ";
            }

            $command = $connection->createCommand($query);
            $results = $command->queryAll();

        }
        if (count($results) == 0 || !$is_utf8) {

            if ($lng == '' && $lat == '') {
                $query = "
                    select *
                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') or c.phone like LOWER('{$phone_keywords}') )
                    limit 50";
            } else {
                $query = "
                    select *,(
                        ROUND(( 3959 * acos( cos( radians($lat) ) *
                                cos( radians( c.lat ) ) *
                                cos( radians( c.lng ) -
                                    radians($lng) ) +
                                sin( radians($lat) ) *
                                sin( radians( c.lat ) ) ) ) ,2)+0.2 )
                        AS distance

                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') or c.phone like LOWER('{$phone_keywords}') )
                    order by distance ASC
                    limit 50";
            }

            $command = $connection->createCommand($query);
            $results = $command->queryAll();
        }

        $ads = array();
        if (count($results) > 0) {
            $zipcode = $results[0]['zipcode'];
            $ads = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.zipcode = '{$zipcode}' and published = 1 order by id DESC")->queryRow();;
        }

        return $this->_response(array('results' => $results, 'many' => count($results) > 1, 'ads' => $ads));

    }

    public function actionComment() {
        $comment = new Comment();
        $comment->email = trim($_POST['email']) != '' ? trim($_POST['email']) : 'Anonymous';
        $comment->username = trim($_POST['username']) != '' ? trim($_POST['username']) : 'Anonymous';
        $comment->content = trim($_POST['content']) != '' ? trim($_POST['content']) : '';
        $comment->created_time = time();
        $comment->company_id = $_POST['company_id'];
        $comment->published = 0;
        $comment->parent_id = 0;
        $comment->like_count = 0;
        $comment->save();

        return $this->_response(array('url' => HSUrl::getCompanyDetailUrl($comment->company_id)));
    }

    public function actionGetComments() {
        $pageIndex = $_GET['index'];

        $id = $_GET['id'];

        $total = Comment::model()->countByAttributes(array(
            'company_id' => $id
        ));
        $comments = Comment::model()->findAll(array(
            'select' => '*',
            'condition' => 'company_id = :id AND published = 1 and parent_id = 0',
            'limit' => 2,
            'offset' => 2 * $pageIndex,
            'order' => 'id DESC',
            'params' => array('id' => $id)
        ));
        $arr = array();
        foreach ($comments as $item) {
            array_push($arr, array(
                'id' => $item->id,
                'username' => $item->username,
                'email' => $item->email,
                'created_time' => HSCommon::calculateTime($item->created_time),
                'content' => $item->content,
                'parent_id' => $item->parent_id,
            ));

        }
        $readMore = 2 * ($pageIndex + 1) <= $total;

        return $this->_response(array('comments' => $arr, 'readmore' => $readMore));

    }

    public function  actionChangeAd() {
        if (!isset($_GET['id'])) return;
        if (!isset($_GET['zipcode'])) return;

        $id = $_GET['id'];
        $zipcode = $_GET['zipcode'];
        $ad = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.id < '{$id}' and a.zipcode = '{$zipcode}' order by id DESC")->queryRow();;
        return $this->_response(array('ad' => $ad));
    }

    public function actionCheckValid() {
        if (!isset($_POST['keywords'])) return;

        $keywords = trim($_POST['keywords']);
        $compare = Compare::model()->findByAttributes(array('value' => $keywords, 'type' => CompareTypeEnum::zip));
        if ($compare != null) return $this->_response(array('error' => 'Vui lòng không chỉ nhập zip code.'));
        return $this->_response(array('success'));
    }
}
